# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入数据的类 ============
from userweb.models import Menu


def index(request):
    return render(request, 'user/menu.html')


def list_values(request):
    # 获取传递的参数
    q_str = request.POST.get('q_str')
    # 获取符合条件的内容
    objs = list(Menu.objects.filter(title__icontains=q_str).values().order_by("order"))
    # 返回
    return JsonResponse({'status': True, 'data': objs})


def add_value(request):
    rec = request.POST
    res = {'status': True}
    try:
        Menu.objects.create(title=rec.get('title'), icon=rec.get('icon'), order=rec.get('order'))
    except Exception as e:
        res['status'] = False
        res['error'] = "添加菜单信息到数据库出现异常，具体原因：" + str(e)

    return JsonResponse(res)


def edit_value(request):
    rec = request.POST
    res = {'status': True}
    try:
        obj = Menu.objects.filter(id=rec.get('id')).first()
        obj.title = rec.get('title')
        obj.icon = rec.get('icon')
        obj.order = rec.get('order')
        obj.save()
    except Exception as e:
        res['status'] = False
        res['error'] = "修改菜单信息到数据库出现异常，具体原因：" + str(e)

    return JsonResponse(res)


def del_value(request):
    id = request.POST.get('id')
    res = {'status': True}
    try:
        Menu.objects.filter(id=id).first().delete()

    except Exception as e:
        res['status'] = False
        res['error'] = "删除菜单信息到数据库出现异常，具体原因：" + str(e)

    return JsonResponse(res)


def get_all_select(request):
    """为下拉框提供数据"""
    # 获取符合条件的内容
    objs = list(Menu.objects.all().values("id", "title").order_by("-order"))
    # 返回
    return JsonResponse({'data': objs})
